extends Sprite

signal select
signal order
signal place_unit

var selected_unit : Unit
var default_tex := preload("res://Assets/cursor.png")
var is_in_deployment_zone : bool = false

onready var world := get_parent()
onready var cam := world.get_node("Camera")
onready var PU := get_parent().get_node("PlayerUnits")
onready var EU := get_parent().get_node("EnemyUnits")
var tm : TileMap

func _process(delta):
	if tm:
		position = tm.get_local_mouse_position() - Vector2(4, 4)
		position = position.snapped(Vector2(8, 8))
	
		if Globals.current_mode == Globals.GAME_MODES.DEPLOYMENT:
			var deploy_zone_ctrl = tm.get_child(0)
			if deploy_zone_ctrl:
				var R = deploy_zone_ctrl.zone_rect.abs()
				if R.has_point(position):
					is_in_deployment_zone = true
				else:
					is_in_deployment_zone = false
			if selected_unit:
				texture = selected_unit.get_sprite()
				if Input.is_action_pressed("ui_cancel"):
					selected_unit = null
			else:
				texture = default_tex
	
	if PU and PU.get_unit_at(position) is Unit:
		modulate = Color(0.4, 0.3, 0.6, 0.6)
	elif EU and EU.get_unit_at(position) is Unit:
		modulate = Color(0.6, 0.3, 0.4, 0.6)
	else:
		modulate = Color(1, 1, 1, 0.6)

func is_unit_there(pos: Vector2 = position):
	return (PU.get_unit_at(pos) is Unit) or (EU.get_unit_at(pos) is Unit)


func _input(event):
	if event is InputEventMouseButton:
		if event.button_index == BUTTON_LEFT and event.pressed:
			if Globals.current_mode == Globals.GAME_MODES.DEPLOYMENT:
				if selected_unit and is_in_deployment_zone:
					emit_signal("place_unit", selected_unit, position)
				else:
					emit_signal("select", position)
			elif Globals.current_mode == Globals.GAME_MODES.PLAY:
					emit_signal("select", position)
		if event.button_index == BUTTON_RIGHT and event.pressed and $"%Selection".unit:
			if Globals.current_mode == Globals.GAME_MODES.PLAY:
				emit_signal("order", position)
